/**
 * @author dhl@oopsplay.org
 *
 */

package controllers;

import play.*;
import play.cache.Cache;
import play.data.validation.Required;
import play.data.validation.Validation;
import play.data.validation.Validation.ValidationResult;
import play.libs.Codec;
import play.libs.Files;
import play.libs.Mail;
import play.mvc.*;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;

import javax.imageio.ImageIO;

import notifiers.Mails;

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;

import models.*;

public class Application extends Controller {

	@Before(only = { "setPass", "setInfo", "setLink" })
	static void isLogin() {
		if (session.get("email") == null) {
			redirect("/");
		}
	}

	public static void index() {

		Logger.info("登录用户邮箱：" + session.get("email"));
		session.put("page", 1);
		User user = Utility.getUser();
		render(user);
	}

	public static void join() {

		// 产生随机的问题
		Long random = new Long(
				(long) (Math.random() * 100 % Question.count() + 1));
		Question question = Question.findById(random);
		// session.put("questionId", question.id);
		Logger.info("随机数为：" + random.toString());
		// Logger.info("放入session的问题id为：" + session.get("questionId"));
		Logger.info("问题为：" + question.question);
		// String ques = question.question;
		render(question);

	}

	// 用户注册，（注意避免邮箱重复注册）
	public static void regist(String email, String answer, Long questionId) {

		Logger.info(questionId.toString());
		validation.required(email).message("邮箱不能为空");

		User olduser = User.find("byEmail", email).first();

		if (olduser == null && !Validation.hasErrors()) {
			// long questionId = 1;
			// chrome下无法或得该session的值，其他浏览器均正常（所以在view通过隐藏区域来达到兼容性）
			// Logger.info("利用session得到的问题id:%s",session.get("questionId"));
			// Logger.info(questionId.toString());
			Question question = Question.findById(questionId);
			validation.email(email);
			if (!Validation.hasErrors()) {

				if (answer.equals(question.answer)) {
					Logger.info("回答正确");
					// 这里需要对邮箱格式进行验证（服务端和客户端都需要）,确保邮件正常发送
					User user = new User(email).save();
					Logger.info(user.uuid);
					Mails.active(user);
					Logger.info("发送成功");
					renderText("请赶快去" + user.email + "激活");

				} else {
					Logger.info("回答错误");
					renderText("对不起答案有误");
				}

			} else {
				renderText("邮箱格式错误");
			}
		} else {
			if (Validation.hasErrors()) {
				renderText(Validation.errors().get(0));
			} else {
				renderText("该邮箱已经注册,忘记密码？");
			}

		}

	}

	// 用户激活
	public static void active(String uuid) {

		User user = User.find("byUuid", uuid).first();
		if (user != null) {
			session.put("email", user.email);
			Logger.info("激活成功，请设置密码");
			Level level = Level.find("byDescription", "见习员").first();
			user.setLevel(level);
			render("Application/passpage.html");
		} else {
			renderText("激活失败");
		}

	}

	public static void passPage() {
		render();
	}

	// 设置密码
	public static void setPass(String oldpass, String pass1, String pass2) {

		User user = Utility.getUser();
		if (user.password == null) {
			Utility.changePass(pass1, pass2);
		} else if (user.password.equals(Codec.hexMD5(oldpass))) {
			Utility.changePass(pass1, pass2);
		} else {
			renderText("原密码有误，请重新输入");
		}
	}

	public static void infoPage() {
		// 仅当密码设置后帐号方可使用

		User user = Utility.getUser();
		if (user.password == null) {
			renderText("激活前请设置密码");
		}
		render();
	}

	// 设置个人信息
	public static void setInfo(String name, String title, String introduction,
			String email) {
		// 注意：该方法中的参数不能直接传递给其他方法

		User user = User.find("byEmail", email).first();
		user.name = name;
		user.title = title;
		user.introduction = introduction;
		user.save();
		renderText("设置成功");

	}

	public static void linkPage() {
		render();
	}

	// 设置链接
	public static void setLink(@Required(message = "网址名称不能为空") String title,
			@Required(message = "网址不能为空") String url) {

		String email = session.get("email");
		if (email != null && !Validation.hasErrors()) {
			// 可以写到model里面
			User user = User.find("byEmail", email).first();
			Link link = Link.find("byTitle", title).first();
			boolean exist = user.links.contains(link);
			if (link != null) {
				// Logger.info(link.title);
				link.url = "http://" + url;
				link.save();
				renderText("修改成功");
			} else {
				if (user.links.size() < 5) {
					user.addLink(title, url);
					user.save();
					renderText("添加成功");
				} else {
					renderText("超过链接上限");
				}

			}

		}
		renderText(validation.errors().get(0));
	}

	// 用户登录
	public static void login(String email, String password) {

		User user = User.find("byEmail", email).first();

		if (user != null) {
			boolean login = user.checkPassword(password);
			Logger.info(user.password);
			if (login) {
				session.put("email", email);
				// renderText("登录成功");
				// 登陆后，用户活跃度加一
				// user.level++;
				user.save();
				renderText("登录成功");
				;
				// redirect("/");
			} else {
				renderText("密码错误");
			}
		} else {
			renderText("用户名错误");
		}

	}

	// 用户注销
	public static void logout() {
		session.clear();
		redirect("/");
	}

	// 忘记密码
	public static void forgetPassword(String email) {
		User user = User.find("byEmail", email).first();
		if (user != null) {

			String password = user.password;
			Logger.info("密码为：" + user.password);
			HtmlEmail htmlemail = new HtmlEmail();
			try {
				htmlemail.addTo(email);
				htmlemail.setFrom("394804487@qq.com");
				htmlemail.setSubject("Use for testing");
				htmlemail.setHtmlMsg("密码是" + password + "请及时登录");
				htmlemail.setTextMsg("Does not support");
				Mail.send(htmlemail);
				Logger.info("发送成功");
				renderText("请赶快去" + user.email + "激活");
			} catch (EmailException e) {
				Logger.info("发送失败");
			}

		} else {
			renderText("该邮箱尚未注册");
		}
	}

	// 用户信息显示
	/**
	 * @param id
	 */
	public static void show(Long id) {
		User user = User.findById(id);
		if (user != null) {
			render(user);
		}
		renderText("用户不存在");

	}

	// 用户个人中心

	public static void dashboard(Long id) {

		if (Utility.checkPermiss(id)) {
			User user = Utility.getUser();
			render(user);
		} else {
			renderText("操作失败");
		}
	}

	// 图片剪裁
	public static void cutImage(int x1, int y1, int width, int height) {

		String email = session.get("email");
		String filename = email.split("@")[0] + ".jpg";
		File filePath = new File("upload/" + email + "/" + filename);
		Logger.info("" + filePath.exists());
		try {
			BufferedImage image = ImageIO.read(filePath);
			int fileWidth = image.getWidth();
			int fileHeight = image.getHeight();
			BufferedImage newImage = new BufferedImage(fileWidth, fileHeight,
					BufferedImage.TYPE_INT_RGB);
			newImage.getGraphics().drawImage(
					image.getScaledInstance(width, height, Image.SCALE_SMOOTH),
					0, 0, null);
			ImageIO.write(image.getSubimage(x1, y1, width, height), "jpg",
					filePath);

			renderText("剪切成功");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Logger.info("剪切出错");
		}

	}

	// App展示页面
	public static void appPage() {

		session.put("page", 2);
		User user = Utility.getUser();
		if (user != null) {
			boolean verified = user.apps.get(0).verified.equals("1");
			if (verified) {
				Logger.info("审核通过");
			}
		}

		List<App> apps = App.find("byVerified", "1").fetch();
		Logger.info("总共app数量：%s", App.count());
		Logger.info("已审核App数量：" + apps.size());
		render(apps, user);
	}

	public static void appDashboard(Long id) {

		if (Utility.checkPermiss(id)) {
			User user = Utility.getUser();
			render(user);
		} else {
			renderText("操作失败");

		}
	}

	/*
	 * 该方法已过期 public static void addApp(String name, File icon, String
	 * description) {
	 * 
	 * validation.required(name).message("app名称不能为空");
	 * validation.required(description).message("app描述不能为空"); User user =
	 * Utility.getUser(); if (!validation.hasErrors()) { App app =
	 * App.find("byName", name).first(); if (app == null) { app = new App(name,
	 * description); app.addUser(user); app.save(); boolean flag =
	 * user.apps.contains(app); Logger.info(flag ? "app添加成功" : "app添加失败"); if
	 * (flag) { renderText("app添加成功"); } renderText("app添加失败"); } else {
	 * renderText("App已存在"); }
	 * 
	 * } renderText(validation.errors().get(0).message());
	 * 
	 * }
	 */

	// 用户图片上传
	public static void uploadImg(File photo, String email) {

		validation.required(photo).message("请选择你要上传的图片");
		User user = User.find("byEmail", email).first();
		Logger.info(email);
		if (!validation.hasErrors()) {
			Logger.info("上传的文件名为：" + photo.getName());
			if (photo.getName().toLowerCase().endsWith("jpg")) {
				String foldername = email;
				// 防止图片冗余
				String photoname = email.split("@")[0] + ".jpg";
				Logger.info("该用户上传目录名为：" + foldername);
				File myfolder = new File(new File("upload"), foldername);
				long filelength = photo.length();
				Logger.info("文件大小为：" + filelength);
				if (!myfolder.exists()) {
					myfolder.mkdir();
					Logger.info("文件成功创建");
				}
				File uploadfile = new File(myfolder, photoname);
				Files.copy(photo, uploadfile);
				user.photo = "upload/" + foldername + "/" + photoname;
				Logger.info("图片地址为：" + user.photo);
				user.save();
				renderText("上传成功");
			}
			renderText("上传失败");
		}
	}

	// 添加application
	public static void addApp(String description, String appname, File icon,
			String email) throws IOException {

		BufferedImage image = ImageIO.read(icon);
		int fileWidth = image.getWidth();
		int fileHeight = image.getHeight();
		Logger.info(fileHeight + "" + fileWidth);
		// 限制图标的尺寸
		if (fileWidth <= 40 && fileHeight <= 40) {
			Logger.info("app介绍" + description);
			validation.required(icon).message("请选择应用图标");
			validation.required(appname).message("应用名称不能为空");
			User user = User.find("byEmail", email).first();
			Logger.info(email + appname);
			if (!validation.hasErrors()) {
				String iconname = appname + ".jpg";
				File destFile = new File(new File(new File("upload"), "icon"),
						iconname);
				Files.copy(icon, destFile);
				Logger.info("上传的文件名为：" + icon.getName());
				App app = App.find("byName", appname).first();
				if (app != null) {
					app.icon = "/upload/icon/" + iconname;
					app.save();
					renderText("修改成功");
				} else {
					app = new App(appname, description);
					app.icon = "/upload/icon/" + iconname;
					app.addUser(user);
					app.save();
					renderText("上传成功");

				}

			}
			renderText("上传失败:%s", validation.errors().get(0));
		}
		renderText("图片大小控制在40×40");

	}

	// 修改application(页面和功能合在一起)
	public static void editApp(long id, String appname, String description) {

		validation.required(appname).message("应用名称不能为空");
		validation.required(description).message("应用描述不能为空");
		App app = App.findById(id);
		if (!validation.hasErrors()) {
			app.name = appname;
			app.description = description;
			app.save();
			renderText("修改成功");
		} else {
			Logger.info(session.get("email"));
			// 只有应用发布者具有修改权限.
			if (app.author.get(0).email.equals(session.get("email"))) {
				render(app);
			}
			renderText("对不起，没有操作权限。");

		}

	}

	// 应用详情页面
	public static void appDetail(long id) {
		App app = App.findById(id);
		render(app);
	}

	// 应用图标修改
	public static void changeIcon(long id, File icon) {
		validation.required(icon).message("应用图标不能为空");
		if (!validation.hasErrors()) {
			App app = App.findById(id);
			String iconName = app.icon.split("/")[3];
			Logger.info(iconName);
			File oldIcon = new File(new File("upload/icon"), iconName);
			Logger.info("" + oldIcon.exists());
			Logger.info("是否已经删除：" + oldIcon.delete());
			File newIcon = new File(new File("upload/icon"), app.name + ".jpg");
			Files.copy(icon, newIcon);
			app.icon = "/upload/icon/" + app.name + ".jpg";
			app.save();
			renderText("应用图标修改成功");
		} else {
			renderText(validation.errors().get(0));
		}

	}

	// 增加作者
	public static void addAuthor(long appId, String name) {
		validation.required(name).message("作者名称不能为空");
		if (!validation.hasErrors()) {
			User author = User.find("byName", name).first();
			if (author != null) {
				App app = App.findById(appId);
				List<User> users = app.author;
				for (int i = 0; i <= users.size(); i++) {
					if (users.get(i).name.equals(name)) {
						renderText("作者已经存在");
					}
				}
				app.addUser(author);
				app.save();
				renderText("作者增加成功");
			} else {
				renderText("用户不存在，范围只限PlayLab成员");
			}
		} else {
			renderText(validation.errors().get(0));
		}

	}

}